﻿;(function ($) {
  var $srcl = $("#yuanwen .srcl"),
      $tgtl = $("#yiwen .tgtl"),
      $cross_over_btn = $(".cross-over-btn"),
      $src_text_area = $(".src-text-area"),
      $target_text_area = $(".target-text-area"),
      $translate_btn = $(".translate-btn"),
      $img_upload_btn = $(".image-upload-btn"),
      $copy_btn = $(".copy_btn"),
      $src_align_text = $(".src-text-align"),
      $target_align_text = $(".target-text-align"),
      $align_wrap = $(".align-wrap");









  init();

  function throttle(method, scope) {
    return function () {
      clearTimeout(method.tId);
      method.tId= setTimeout(function(){
        method.call(scope);
      }, 400);
    }
  }

  function handleTranslateText() {
    var srcl = $srcl.attr("data-lang"),
        tgtl = $tgtl.attr("data-lang"),
        text = $.trim($src_text_area.val());
    
    if(text == ''){
    	$target_text_area.val('');
		$('#box1').show();
		$('#box2').hide();	
		return;
    }
    //console.log(text);
    /*
	try {
	    netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead");
	} catch (e) {
	    console.log(e);
	} 
	
	*/
    $.ajax({
      url: "http://translateport.yeekit.com/translate",
      type: "POST",
      data: {
        "srcl": srcl,
        "tgtl": tgtl,
        "text": text,
        "detoken": true,
        "align": true
      },
      dataType: "json",  
      success: function (result) {
        var data = result.translation[0].translated[0],
            srcArr = data["src-tokenized"].split(" "),
            //if(srcl == 'en'||srcl=='zh'){
            		targetArr = data["tgt-tokenized"].split(" "),
            //}else{
            	 //targetArr = data["tgt-tokenized"].split(//),
            //}
            responeText = data.text,
            len = data["alignment-raw"].length,
            baseNum = new Date().getTime(),
            srcTplArr = [],
            targetTplArr = [],
            tplStr = "",
            alignData;

        $(".fanyi_xxbox").fadeIn(0);
        $('#box1').hide();
        $target_text_area.val(responeText);

        srcTplArr.push('<p>');
        targetTplArr.push('<p>');

        for(var i = 0; i < len; i++) {
          alignData = data["alignment-raw"][i];

          srcTplArr.push('<span id="' + (baseNum + i) + '-src">' + srcArr.slice(alignData['src-start'], alignData['src-end'] + 1).join(srcl === 'zh' ? '' : ' ') + '</span>');

          targetTplArr.push('<span id="' + (baseNum + i) + '">' + targetArr.slice(alignData['tgt-start'], alignData['tgt-end'] + 1).join(tgtl === 'zh' ? '' : ' ') + '</span>');
        }

        srcTplArr.push('</p>');
        targetTplArr.push('</p>');

        $align_wrap.empty().append(srcTplArr.join(srcl === 'zh' ? '' : ' ')).append(targetTplArr.join(tgtl === 'zh' ? '' : ' '));

      }
    });
    
  }

  function handleCrossOverLang() {
    var src_text = $srcl.text(),
        src_lang = $srcl.attr("data-lang"),
        target_text = $tgtl.text(),
        target_lang = $tgtl.attr("data-lang");

    if (src_text === "自动检测") {return false;}

    $srcl.text(target_text).attr("data-lang", target_lang);
    $tgtl.text(src_text).attr("data-lang", src_lang);
  }

  function handleDetectionLanguage() {
    $.ajax({
      url: "http://translateport.yeekit.com:9006/detection",
      type: "POST",
      data: {
        "text": $src_text_area.val()
      },
      dataType: "json",  
      success: function (result) {
        debugger
      }
    });
  }

  function loadPlugins() {
    $("#pagepiling").pagepiling({
      menu: "#menu",
      anchors: ["page1", "page2", "page3"],
      sectionsColor: ["#ffffff", "#41b860", "#3eb3e4"]
    });
    $copy_btn.zclip({
      path: "js/ZeroClipboard.swf", 
      copy: function(){
        return $target_text_area.val();
      }
    });
  }

  function bindEvents() {
    $src_text_area.on("keyup", throttle(handleTranslateText));
    $translate_btn.on("click", throttle(handleTranslateText));
    $cross_over_btn.on("click", handleCrossOverLang);
    $align_wrap.delegate("span", "mouseover", function () {
      var id = $(this).attr("id"),
          arr = id.split("-"),
          $target,
          num;

      if (arr.length > 0) {
        num = arr[0];
        $target = $align_wrap.find("#" + num);
      } else {
        num = id;
        $target = $align_wrap.find("#" + num + "-src");
      }

      $(this).add($target).addClass("hover");
    });
    $align_wrap.delegate("span", "mouseout", function () {
      var id = $(this).attr("id"),
          arr = id.split("-"),
          $target,
          num;

      if (arr.length > 0) {
        num = arr[0];
        $target = $align_wrap.find("#" + num);
      } else {
        num = id;
        $target = $align_wrap.find("#" + num + "-src");
      }

      $(this).add($target).removeClass("hover");
    });

    var triClicked = false;
    
    var srcTriClicked = false;
    
    $("#srcTri").click(function(){
    	srcTriClicked = true;
    	triClicked = true;
    	if($("#yuanwenmore").is(':visible')){
    		$("#yuanwenmore").hide();
    	}else{
    		$("#yuanwenmore").show();
    	}
      
    	$("#yiwenmore").hide();
    });
    
    $("#yuanwen").click(function(){
    	if(!srcTriClicked){
    		triClicked = true;
	    	if($("#yuanwenmore").is(':visible')){
	    		$("#yuanwenmore").hide();
	    	}else{
	    		$("#yuanwenmore").show();
	    	}
	      
	    	$("#yiwenmore").hide();
    	}
    });
    
    $("#yuanwenmore a").click(function(){
      $("#yuanwenmore").hide();
      $srcl.text($(this).text()).attr("data-lang", $(this).attr("data-lang"));

      if ($(this).text() === "自动检测") {
        // 绑定自动检测事件
        $src_text_area.on("change", handleDetectionLanguage);
      } else {
        $src_text_area.off("change", handleDetectionLanguage);
		//赋值到新的源语言选择区域
		$("#yuanwenlangSelected").html($(this).text());
      }
    });
    
    var targetTriClicked = false;
    
    $("#targetTri").click(function(){
    	targetTriClicked = true;
    	triClicked = true;
    	if($("#yiwenmore").is(':visible')){
    		$("#yiwenmore").hide();
    	}else{
    		$("#yiwenmore").show();
    	}
      
    	$("#yuanwenmore").hide();
    });

    $("#yiwen").click(function(){
    	if(!targetTriClicked){
    		triClicked = true;
	    	if($("#yiwenmore").is(':visible')){
	    		$("#yiwenmore").hide();
	    	}else{
	    		$("#yiwenmore").show();
	    	}
	      
	    	$("#yuanwenmore").hide();
    	}
    });
    $("#yiwenmore a").click(function(){
      $("#yiwenmore").hide();
      $tgtl.text($(this).text()).attr("data-lang", $(this).attr("data-lang"));
    });
    /*
    $(".shouqi").click(function(){
      $("#yiwenmore").hide();
      $("#yuanwenmore").hide();
    });
    */
    /*
    $('#main').click(function(){
    	if(!triClicked){
    		$("#yiwenmore").hide();
    		$("#yuanwenmore").hide();
    	}
    });
    */
  }

  function init() {
    loadPlugins();
    bindEvents();
  }


})(jQuery);